# -*- coding: utf-8 -*-
from django import forms
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
import json
from xadmin.widgets import AdminSelectWidget, AdminTextInputWidget


class Qrcode(AdminTextInputWidget):
    template_name = 'qrcode.html'


class ScanInput(forms.Select):
    # 继承已有的forms.Select是因为xadmin是根据原有的widget来生成页面，不会影响数据的增删改查等逻辑。如果自定义form，只为了显示和验证可只继承form，需要和model关联则需要继承modelform
    #
    # template_name = 'django/forms/widgets/text.html'
    template_name = 'scan_input.html'
    pass
    # class TextInput():
    #     template_name = 'django/forms/widgets/text.html'

    # template_name = 'django/forms/widgets/text.html'
    # def render(self, name, value, attrs=None):
    #     context = {}
    #     return mark_safe(render_to_string(self.template_name, context))


class ScanSelect(AdminSelectWidget):
    # 继承已有的forms.Select是因为xadmin是根据原有的widget来生成页面，不会影响数据的增删改查等逻辑。如果自定义form，只为了显示和验证可只继承form，需要和model关联则需要继承modelform
    # AdminSelectWidget foreignfield默认的widget，继承的就是forms.Select

    # template_name = 'django/forms/widgets/select.html'
    # option_template_name = 'django/forms/widgets/select_option.html'
    template_name = 'scan_select.html'
    option_template_name = 'scan_select_option.html'

    def get_context(self, name, value, attrs):
        context = super(AdminSelectWidget,self).get_context(name, value, attrs)
        context["optgroups_json"] = json.dumps(context["widget"]["optgroups"])
        context["widget_json"] = json.dumps(context["widget"])
        return context



    # xadmin / widgets.py
    # class AdminSelectWidget(forms.Select):
    #
    #     @property
    #     def media(self):
    #         return vendor('select.js', 'select.css', 'xadmin.widget.select.js')

    # xadmin / widgets.py
    # class Select(ChoiceWidget):
    #     input_type = 'select'
    #     template_name = 'django/forms/widgets/select.html'
    #     option_template_name = 'django/forms/widgets/select_option.html'
    #     def subwidgets(self, name, value, attrs=None):
    #         context = self.get_context(name, value, attrs)
    #         yield context['widget']
    #     ......

    # xadmin / widgets.py
    # class ChoiceWidget(Widget):
    #     allow_multiple_selected = False
    #     input_type = None
    #     template_name = None
    #     option_template_name = None
    #     add_id_index = True
    #     checked_attribute = {'checked': True}
    #     option_inherits_attrs = True
    #     def subwidgets(self, name, value, attrs=None):
    #         """
    #         Yield all "subwidgets" of this widget. Used to enable iterating
    #         options from a BoundField for choice widgets.
    #         """
    #         value = self.format_value(value)
    #         for option in self.options(name, value, attrs):
    #             yield option
    #     ......